/**
 * 用于主进程与渲染进程间通信的辅助插件
 * 依赖于electron ipcRenderer
 * 基于 https://github.com/feng-fu/electron-ipc-demo 修改
 */

import { ipcRenderer } from 'electron'
const {
  UI_NORMAL_MSG,
  DB_NORMAL_MSG
} = require('../../src-electron/constants')

const ipcService = Object.create(null)
const callbackCache = {}

ipcService.install = Vue => {
  addChannel(Vue, '$db', DB_NORMAL_MSG, UI_NORMAL_MSG)
}

export default ipcService

/**
 * 添加信道
 * @param {string} name 信道名
 * @param {string} on 监听信道
 * @param {string} send 发送信道
 */
const addChannel = (Vue, name, on, send) => {
  callbackCache[name] = []

  Vue.prototype[name] = {
    // 发送
    send: (type, data) => {
      try {
        ipcRenderer.send(send, {
          type,
          data
        })
        return true
      } catch (e) {
        console.error(e)
        return false
      }
    },
    // 添加
    on: (type, callback) => {
      // 防止重复添加
      if (callbackCache[name].findIndex(v => v.type === type) > -1) return
      callbackCache[name].push({
        type,
        callback
      })
    },
    // 删除
    off: type => {
      const index = callbackCache[name].findIndex(v => v.type === type)
      if (index > -1) {
        callbackCache[name].splice(index, 1)
      } else {
        console.error(`error type ${type}`)
      }
    }
  }
  // 监听主进程消息
  ipcRenderer.on(on, (sender, msg) => {
    callbackCache[name].forEach(cache => {
      if (cache.type === msg.type) {
        cache.callback && cache.callback(msg.data)
      }
    })
  })
}
